package com.fresh.liangyi.controller.user;

import com.fresh.liangyi.model.domain.User;
import com.fresh.liangyi.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.RepositoryDefinition;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Controller
@Slf4j
public class RegisterController {
    @Autowired
    private UserService userService;
    @GetMapping("/register")
    public String register(){
        return "comm/register";
    }
    @PostMapping("/register")
    @ResponseBody
    public String register(@RequestParam String username,
                           @RequestParam String password,
                           @RequestParam String repassword,
                           @RequestParam String email,
                           @RequestParam String tel_phone){
        if(!password.equals(repassword)){
            return "passwordFail";
        }
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        //创建User
        User user=new User();
        user.setCreateTime(new Date());
        user.setUsername(username);
        user.setPassword(encoder.encode(password));
        user.setEmail(email);
        user.setTelPhone(tel_phone);
        if(userService.addUser(user)>0){
            userService.addAuthorityByUser(user.getId(),2);
            return "success";
        }else{
            return "fail";
        }

    }

}
